import Vue from 'vue'
import VueRouter from "vue-router";
import Index from "../views/Index";
import Blogs from "../components/Blogs";
import Login from "../components/Login";
import Resetpw from "../views/Resetpw";
import BlogDetail from "../components/BlogDetail";
import Search from "../components/Search";
import Admin from "../views/Admin"
import ArticleList from "../components/ArticleList";
import Write from "../views/Write";
//在当前模块中引入store
import store from "../store/index";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/index'
    },
    {
        path: '/index',
        component: Index,
        children: [
            {
                path: '',
                component: Blogs,
            },
            {
                path: 'login',
                component: Login
            },
            {
                path: '/blog',
                name: 'BlogDetail',
                component: BlogDetail
            },
            {
                path: 'search',
                name: 'Search',
                component: Search
            }
        ]
    },
    {
        path: '/forgetpw',
        component: Resetpw
    },
    {
        path: '/admin',
        component: Admin,
        meta: {
            needLogin: true
        },
        children: [
            {
                path: '',
                component: ArticleList,
                meta: {
                    needLogin: true
                }
            },
            {
                path: 'write',
                name: 'Write',
                component: Write,
                meta: {
                    needLogin: true
                }
            }
        ]

    },
]

const router = new VueRouter({
    routes,
})

router.beforeEach((to,from,next)=>{
    if(to.meta.needLogin){
        if(store.state.token){
            next();
        }else {
            alert('您还没有登录，禁止访问！');
            next('/index/login');
        }
    }else{
        next();
    }
})

export default router